package com.darren.center.design.patterns.utils;

import com.darren.center.design.patterns.exceptions.ApiBizException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <h3>design-patterns</h3>
 * <p></p>
 *
 * @author : Darren
 * @date : 2021年06月14日 19:59:28
 **/
public class XMLParser {

    public static Map<String, Object> getMapFromXML(String xmlString) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream is = new ByteArrayInputStream(xmlString.getBytes());
            Document document = builder.parse(is);

            // 获取到document里面的全部结点
            NodeList allNodes = document.getFirstChild().getChildNodes();
            Node node;
            Map<String, Object> map = new HashMap<>();
            int i = 0;
            while (i < allNodes.getLength()) {
                node = allNodes.item(i);
                if (node instanceof Element && StringUtils.isNotBlank(node.getNodeName())){
                    map.put(node.getNodeName(), node.getTextContent());
                }
                i++;
            }
            return map;
        } catch (Exception e) {
            throw new ApiBizException(ApiBizException.DEFAULT_CODE, "XML转换错误");
        }

    }

}

